package com.client.ws.mcp;

import com.alibaba.fastjson2.JSON;
import io.modelcontextprotocol.client.McpSyncClient;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author WuFengSheng
 * @date 2025/4/19 10:14
 */
@Slf4j
@Service
public class ChatService {

    private final ChatClient chatClient;

    @Getter
    private final ToolCallback[] toolCallbacks;

    public ChatService(OpenAiChatModel openAiChatModel, List<McpSyncClient> mcpSyncClientList) {
        log.info("mcpSyncClientList={}", JSON.toJSONString(mcpSyncClientList));
        log.info("===============================================\n");
        for (McpSyncClient mcpSyncClient : mcpSyncClientList) {
            log.info("clientInfo={}", mcpSyncClient.getClientInfo());
            log.info("serverInfo={}", mcpSyncClient.getServerInfo());
        }
        log.info("===============================================\n");
        var mcpToolCallbackProvider = new SyncMcpToolCallbackProvider(mcpSyncClientList);
        toolCallbacks = mcpToolCallbackProvider.getToolCallbacks();
        log.info("toolCallbacks={}", JSON.toJSONString(toolCallbacks));
        log.info("===============================================\n");
        for (ToolCallback toolCallback : toolCallbacks) {
            log.info("toolCallback={}", JSON.toJSON(toolCallback.getToolDefinition()));
        }
        log.info("===============================================\n");
        this.chatClient = ChatClient.builder(openAiChatModel)
                .defaultTools(mcpToolCallbackProvider)
                .build();
    }

    public String askQuestion(String prompt) {
        return chatClient.prompt(prompt).call().content();
    }

}
